from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from ..db import get_db
from .. import models, schemas
from ..security import get_current_user

router = APIRouter()

@router.post("/", response_model=schemas.GroupOut)
def create_group(payload: schemas.GroupCreate, db: Session = Depends(get_db), current=Depends(get_current_user)):
    g = models.Group(name=payload.name, description=payload.description, owner_id=current.id)
    db.add(g)
    db.commit()
    db.refresh(g)
    return g

@router.post("", response_model=schemas.GroupOut)
def create_group_noslash(payload: schemas.GroupCreate, db: Session = Depends(get_db), current=Depends(get_current_user)):
    """Alias without trailing slash to avoid 307 redirect from /api/groups to /api/groups/ on POST."""
    return create_group(payload, db, current)


@router.get("/", response_model=List[schemas.GroupOut])
def list_groups(db: Session = Depends(get_db), current=Depends(get_current_user)):
    return db.query(models.Group).filter(models.Group.owner_id == current.id).all()


@router.get("", response_model=List[schemas.GroupOut])
def list_groups_noslash(db: Session = Depends(get_db), current=Depends(get_current_user)):
    """Alias without trailing slash to avoid 307 redirect between /api/groups and /api/groups/."""
    return list_groups(db, current)

@router.put("/{group_id}", response_model=schemas.GroupOut)
def update_group(group_id: int, payload: schemas.GroupCreate, db: Session = Depends(get_db), current=Depends(get_current_user)):
    g = db.query(models.Group).filter(models.Group.id == group_id, models.Group.owner_id == current.id).first()
    if not g:
        raise HTTPException(status_code=404, detail="Group not found")
    g.name = payload.name
    g.description = payload.description
    db.commit()
    db.refresh(g)
    return g

@router.delete("/{group_id}")
def delete_group(group_id: int, db: Session = Depends(get_db), current=Depends(get_current_user)):
    g = db.query(models.Group).filter(models.Group.id == group_id, models.Group.owner_id == current.id).first()
    if not g:
        raise HTTPException(status_code=404, detail="Group not found")
    db.delete(g)
    db.commit()
    return {"ok": True}
